<style lang="less">
@import "./main.less";
.ivu-modal-body {
  padding-top: 6px;
}
.new-event-tips-bar {
  display: block;
  height: 30px;
  margin-left: -16px;
  margin-right: -16px;
  padding-left: 30px;
  padding-right: 15px;
  color: rgba(105, 120, 135, 0.65);
  line-height: 30px;
  font-size: 12px;
  background-color: #fffbe6;
  border: 1px solid #ffe58f;
  a {
    text-decoration: none;
    color: #95989d;
  }
  span {
    color: #ce5f5d;
  }
}
.base-info {
  padding: 16px;
  padding-top: 0;
  border-bottom: 1px solid #e6ebf0;
  .info-title {
    color: #5a5e66;
  }
  .title {
    margin-right: 5px;
    font-size: 14px;
    color: #adb6ca;
    font-style: normal;
  }
}
</style>

<template>
  <div class="main" :class="{'main-hide-text': shrink}">
    <div class="main-header-con">
      <div class="main-header">
        <!--<div class="navicon-con">
          <Button
            :style="{transform: 'rotateZ(' + (this.shrink ? '-90' : '0') + 'deg)'}"
            type="text"
            @click="toggleClick"
          >
            <Icon type="md-menu" size="32"></Icon>
          </Button>
        </div>-->
        <div class="header-middle-con">
          <div class="main-breadcrumb" v-if="navType==4">
            <breadcrumb-nav :currentPath="currentPath"></breadcrumb-nav>
          </div>
          <div class="main-nav-menu" v-if="navType==1||navType==2" style="width: 80%;">
            <!-- <img
              src="../assets/xboot.jpg"
              width="160px"
              height="100%"
              style="float: left; padding: 8px 0px;"
            />-->
            <div
              class
              style="height: 60px; margin-right: 16px; display: flex; flex-direction: column; float: left;"
            >
              <span
                style="height: 60px; font-family: 'Microsoft YaHei'; font-style: oblique; font-size: 22px; line-height: 60px;"
              >光缆管理定位平台</span>
            </div>

            <div class style="height: 60px;float: right; margin-right: 16px;">
              <Menu mode="horizontal" :active-name="currNav" @on-select="selectNav">
                <MenuItem v-for="(item, i) in navList" :key="i" :name="item.name">
                  <Icon :type="item.icon" style="margin-bottom:3px;" v-if="navType==1" />
                  {{item.title}}
                </MenuItem>
              </Menu>
            </div>
          </div>
          <div class="main-nav" v-if="navType==3" style="width: 20%;">
            <Dropdown transfer @on-click="selectNav">
              <div style="cursor: pointer">
                {{currNavTitle}}
                <Icon type="ios-arrow-down"></Icon>
              </div>
              <DropdownMenu slot="list">
                <DropdownItem
                  v-for="(item, i) in navList"
                  :key="i"
                  :name="item.name"
                  :selected="currNav==item.name"
                >
                  <div class="nav-item">
                    <Icon
                      :type="item.icon"
                      :size="16"
                      class="ivu-row-flex ivu-row-flex-middle ivu-row-flex-center"
                      style="margin: 0 10px 3px 0"
                    ></Icon>
                    {{item.title}}
                  </div>
                </DropdownItem>
              </DropdownMenu>
            </Dropdown>
          </div>
        </div>
        <div :class="{'header-avator-con':navType!=4, 'header-avator-con nav4':navType==4}">
          <Dropdown @on-click="selectNav" class="options" v-if="navType==4">
            <Icon type="ios-apps" :size="24" class="language"></Icon>
            <DropdownMenu slot="list">
              <DropdownItem
                v-for="(item, i) in navList"
                :key="i"
                :name="item.name"
                :selected="currNav==item.name"
              >
                <div>
                  <Icon :type="item.icon" :size="14" style="margin: 0 10px 2px 0"></Icon>
                  {{item.title}}
                </div>
              </DropdownItem>
            </DropdownMenu>
          </Dropdown>
          <full-screen v-model="isFullScreen" @on-change="fullscreenChange"></full-screen>

          <!-- <Dropdown @on-click="handleLanDropdown" class="options">
            <Icon type="md-globe" :size="24" class="language"></Icon>
            <DropdownMenu slot="list">
              <DropdownItem name="zh-CN">中文</DropdownItem>
              <DropdownItem name="en-US">English</DropdownItem>
            </DropdownMenu>
          </Dropdown>-->
          <lock-screen></lock-screen>
          <span style="color: #e8ad4f;">报警提示</span>
          <i-switch v-model="isSocketConnected">
            <span slot="open">开</span>
            <span slot="close">关</span>
          </i-switch>
          <!-- <message-tip v-model="mesCount"></message-tip> -->
          <div class="user-dropdown-menu-con">
            <Row type="flex" justify="end" align="middle" class="user-dropdown-innercon">
              <Dropdown transfer trigger="hover" @on-click="handleClickUserDropdown">
                <a
                  class="ivu-row-flex ivu-row-flex-middle ivu-row-flex-center"
                  href="javascript:void(0)"
                >
                  <span class="main-user-name">{{ username }}</span>
                  <Icon type="md-arrow-dropdown" />
                  <Avatar :src="avatarPath" style="background: #619fe7;margin-left: 10px;"></Avatar>
                </a>
                <DropdownMenu slot="list">
                  <DropdownItem name="ownSpace">{{ $t('userCenter') }}</DropdownItem>
                  <DropdownItem name="changePass">{{ $t('changePass') }}</DropdownItem>
                  <DropdownItem name="loginout" divided>{{ $t('logout') }}</DropdownItem>
                </DropdownMenu>
              </Dropdown>
            </Row>
          </div>
        </div>
      </div>
    </div>

    <div class="middle-main" :style="{height:contentHeight+'px'}">
      <span
        @click="toggleClick"
        class="left-arrow"
        :class="{ 'active': shrink}"
        id="menu-left-arrow"
        style="display: block;"
      ></span>
      <div
        style="float:left;height:100%;transition: transform .3s;"
        :style="{width: shrink?'60px':'220px', overflow: shrink ? 'visible' : 'auto'}"
      >
        <div
          class="sidebar-menu-con menu-bar"
          style="transition: transform .3s;"
          :style="{width: shrink?'60px':'220px', overflow: shrink ? 'visible' : 'auto'}"
        >
          <shrinkable-menu
            :shrink="shrink"
            @on-change="handleSubmenuChange"
            :theme="menuTheme"
            :before-push="beforePush"
            :open-names="openedSubmenuArr"
            :menu-list="menuList"
          ></shrinkable-menu>
        </div>
      </div>
      <div>
        <div class="tags-con" :style="{left: shrink?'60px':'220px'}">
          <tags-page-opened :shrink="shrink" :pageTagsList="pageTagsList"></tags-page-opened>
        </div>
        <div class="single-page-con" :style="{left: shrink?'60px':'220px'}">
          <div class="single-page">
            <keep-alive :include="cachePage">
              <router-view></router-view>
            </keep-alive>
          </div>
        </div>
      </div>
    </div>
    <!-- 全局加载动画 -->
    <circleLoading class="loading-position" v-show="loading" />
    <audio id="audioPlay" src="static/119.ogg" controls="controls" style="display:none;"></audio>
    <Modal
      title="报警"
      v-model="modalVisible"
      :mask-closable="false"
      :width="550"
      :styles="{top: '200px'}"
      :footer-hide="true"
    >
      <div>
        <div class="base-info">
          <h3 class="info-title">{{currentEvent.plateNum}}</h3>
          <div>
            <span class="title">SIM卡号:</span>
            <span class="content">{{currentEvent.simCard}}</span>
          </div>
          <div>
            <span class="title">报警类型:</span>
            <span class="content">{{currentEvent.alarmTypeDetail}}</span>
          </div>
          <div>
            <span class="title">时间:</span>
            <span class="content">{{currentEvent.alarmTime}}</span>
          </div>
        </div>
      </div>
    </Modal>
  </div>
</template>

<script>
import shrinkableMenu from "./main-components/shrinkable-menu/shrinkable-menu.vue";
import tagsPageOpened from "./main-components/tags-page-opened.vue";
import breadcrumbNav from "./main-components/breadcrumb-nav.vue";
import fullScreen from "./main-components/fullscreen.vue";
import lockScreen from "./main-components/lockscreen/lockscreen.vue";
import messageTip from "./main-components/message-tip.vue";
import circleLoading from "@/views/my-components/circle-loading.vue";
import Cookies from "js-cookie";
import util from "@/libs/util.js";
import config from "@/config";
const BASE_URL =
  process.env.NODE_ENV === "development"
    ? config.baseUrl.dev
    : config.baseUrl.pro;

import { startVideo, endVideo, dealEvent } from "@/api/monitor";
import { answerOversee } from "@/api/index";
export default {
  components: {
    shrinkableMenu,
    tagsPageOpened,
    breadcrumbNav,
    fullScreen,
    lockScreen,
    messageTip,
    circleLoading
  },
  data() {
    return {
      submitLoading: false,
      currentEvent: {
        carId: 3,
        plateNum: "粤B12115",
        simCard: "13512112345",
        alarmTypeDetail: "紧急报警",
        alarmTime: "2019-10-22 15:50:36"
      },
      modalVisible: false,
      isSocketConnected: true,
      mysocket: null,
      contentHeight: 800,
      shrink: false,
      username: "",
      userId: "",
      isFullScreen: false,
      openedSubmenuArr: this.$store.state.app.openedSubmenuArr,
      firstThreeNav: [],
      lastNav: [],
      navType: 1,
      currNav: ""
    };
  },
  computed: {
    loading() {
      return this.$store.state.app.loading;
    },
    navList() {
      return this.$store.state.app.navList;
    },
    // currNav() {
    //   return this.$store.state.app.currNav
    // },
    currNavTitle() {
      return this.$store.state.app.currNavTitle;
    },
    menuList() {
      return this.$store.state.app.menuList;
    },
    pageTagsList() {
      return this.$store.state.app.pageOpenedList; // 打开的页面的页面对象
    },
    currentPath() {
      return this.$store.state.app.currentPath; // 当前面包屑数组
    },
    avatarPath() {
      return localStorage.avatorImgPath;
    },
    cachePage() {
      return this.$store.state.app.cachePage;
    },
    lang() {
      return this.$store.state.app.lang;
    },
    menuTheme() {
      return this.$store.state.app.menuTheme;
    },
    mesCount() {
      return this.$store.state.app.messageCount;
    }
  },
  stompClient: {
    monitorIntervalTime: 100,
    stompReconnect: true,
    timeout(orgCmd) {}
  },
  methods: {
    init() {
      let pathArr = util.setCurrentPath(this, this.$route.name);
      // this.$store.commit("updateMenulist");
      if (pathArr.length >= 2) {
        this.$store.commit("addOpenSubmenu", pathArr[1].name);
      }
      let userInfo = JSON.parse(Cookies.get("userInfo"));
      this.username = userInfo.username;
      this.userId = userInfo.id;
      this.checkTag(this.$route.name);
      // this.socketConn();
    },
    selectNav(name) {
      this.$store.commit("setCurrNav", name);
      this.setStore("currNav", name);
      // 清空所有已打开标签
      // this.$store.commit("clearAllTags");
      // this.$router.push({
      //   name: 'home_index'
      // })

      util.initRouter(this);
    },
    toggleClick() {
      this.shrink = !this.shrink;
    },
    handleLanDropdown(name) {
      this.$i18n.locale = name;
      this.$store.commit("switchLang", name);
    },
    handleClickUserDropdown(name) {
      if (name == "ownSpace") {
        util.openNewPage(this, "ownspace_index");
        this.$router.push({
          name: "ownspace_index"
        });
      } else if (name == "ownSpaceOld") {
        util.openNewPage(this, "ownspace_old");
        this.$router.push({
          name: "ownspace_old"
        });
      } else if (name == "changePass") {
        util.openNewPage(this, "change_pass");
        this.$router.push({
          name: "change_pass"
        });
      } else if (name == "loginout") {
        // 退出登录
        this.$store.commit("logout", this);
        this.$store.commit("clearOpenedSubmenu");
        this.setStore("token", "");
        // 强制刷新页面 重新加载router
        location.reload();
      }
    },
    checkTag(name) {
      let openpageHasTag = this.pageTagsList.some(item => {
        if (item.name == name) {
          return true;
        }
      });
      if (!openpageHasTag) {
        //  解决关闭当前标签后再点击回退按钮会退到当前页时没有标签的问题
        util.openNewPage(
          this,
          name,
          this.$route.params || {},
          this.$route.query || {}
        );
      }
    },
    handleSubmenuChange(val) {
      //  console.log(val)
    },
    beforePush(name) {
      // console.log(name)
      return true;
    },
    fullscreenChange(isFullScreen) {
      // console.log(isFullScreen);
    },
    socketConn() {
      let socketUrl = BASE_URL.split("/")[2];
      let deptId = this.getStore("deptId");
      let self = this;
      // 重连
      function reconnect(url) {
        if (self.lockReconnect) return;
        self.lockReconnect = true;
        setTimeout(function() {
          //没连接上会一直重连，设置延迟避免请求过多
          createWebSocket(url);
          self.lockReconnect = false;
        }, 2000);
      }
      // 实例websocket
      function createWebSocket(url) {
        try {
          if ("WebSocket" in window) {
            self.mysocket = new WebSocket(url);
          } else if ("MozWebSocket" in window) {
            self.mysocket = new MozWebSocket(url);
          } else {
            self.$Message.error(
              "当前浏览器不支持websocket协议,建议使用现代浏览器",
              3000
            );
          }
          initEventHandle(url);
        } catch (e) {
          reconnect(url);
        }
      }
      let heartCheck = {
        timeout: 5 * 1000, //  心跳检测时长
        timeoutObj: null, // 定时变量
        reset: function() {
          // 重置定时
          clearTimeout(this.timeoutObj);
          return this;
        },
        start: function() {
          // 开启定时

          this.timeoutObj = setTimeout(function() {
            // 心跳时间内收不到消息，主动触发连接关闭，开始重连
            if (self.mysocket) {
              self.mysocket.send("888");
            }

            // self.mysocket.close();
          }, this.timeout);
        }
      };

      // 初始化事件函数
      function initEventHandle(wsUrl) {
        self.mysocket.onclose = function() {
          if (self.mysocket) {
            self.mysocket.close();
            console.log("Socket已关闭");
            reconnect(wsUrl);
          }
        };
        self.mysocket.onerror = function(err) {
          reconnect(wsUrl);
        };
        self.mysocket.onopen = function() {
          console.log("Socket 已打开");
          heartCheck.reset().start(); //心跳检测重置
        };
        self.mysocket.onmessage = function(msg) {
          //如果获取到消息，心跳检测重置
          heartCheck.reset().start(); //拿到任何消息都说明当前连接是正常的

          if (msg.data !== "heartbeat") {
            self.currentEvent = JSON.parse(msg.data);
            self.modalVisible = true;
            console.log(JSON.parse(msg.data));
          }
        };
      }

      createWebSocket(`ws://${socketUrl}/vietnamcar/websocket/${deptId}`);
    }
  },
  watch: {
    $route(to) {
      this.$store.commit("setCurrentPageName", to.name);
      let pathArr = util.setCurrentPath(this, to.name);
      if (pathArr.length > 2) {
        this.$store.commit("addOpenSubmenu", pathArr[1].name);
      }
      this.checkTag(to.name);
      localStorage.currentPageName = to.name;
    },
    lang() {
      util.setCurrentPath(this, this.$route.name); // 在切换语言时用于刷新面包屑
    }
  },
  mounted() {
    this.init();
    this.contentHeight = window.innerHeight - 62;
    // 然后监听window的resize事件．在浏览器窗口变化时再设置下高度．
    const that = this;
    window.addEventListener("resize", function() {
      that.contentHeight = window.innerHeight - 62;
    });
    let self = this;

    setTimeout(function() {
      self.currNav = self.$store.state.app.currNav;
    }, 100);
  },
  created() {
    // 显示打开的页面的列表
    this.$store.commit("setOpenedList");
  },
  destroyed() {
    this.mysocket.close();
  }
};
</script>
